import axios from 'axios'
import store from '../store/index'
import router from '../router/index'
import {
    MessageBox
} from 'element-ui';


// 超时时间
axios.defaults.timeout = 5000;

axios.defaults.baseURL = 'http://localhost:8080';
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

//为每次请求添加请求头
axios.interceptors.request.use(
    config => {
        if (sessionStorage.getItem("token")) {
            config.headers['Authorization'] = sessionStorage.getItem("token");
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

//设置token拦截器
axios.interceptors.response.use(
    (response) => {
        if (response) {
            switch (response.data.code) {
                case 400:
                    MessageBox.alert("身份验证失败，请重新登录", '提示', {
                        confirmButtonText: '确定',
                        callback: action => { // eslint-disable-line no-unused-vars
                            store.dispatch('Logout').then(() => {
                                //跳转到登录页面  
                                router.replace({
                                    path: '/'
                                });
                            });
                        }
                    });
                    break;
                case 401:
                    MessageBox.alert("请登录后在进行访问", '提示', {
                        confirmButtonText: '确定',
                        callback: action => { // eslint-disable-line no-unused-vars
                            store.dispatch('Logout').then(() => {
                                //跳转到登录页面  
                                router.replace({
                                    path: '/'
                                });
                            });
                        }
                    });
                    break;
            }

        }
        return response;
    },
    (error) => {
        if (error.response) {
            MessageBox.alert("身份验证失败，请重新登录", '提示', {
                confirmButtonText: '确定',
                callback: action => { // eslint-disable-line no-unused-vars
                    store.dispatch('Logout').then(() => {
                        //跳转到登录页面  
                        router.replace({
                            path: '/'
                        });
                    });
                }
            });
            return error;
        }
    }
);

export default axios